<template>
    <div class="slide-menu-2">
       <div class="model-top">
         <el-button type="text" @click="addShowDialog" icon="el-icon-circle-plus" class="addBtn">新建子模块</el-button>
       </div>
        <ul class="model-menu-ul">
          <li v-for="(item, index) in list" :key="index" :class="{'current-li': item.id === currentId}" @click="handleClickItem(item.id)">
            <router-link to="/" class="f_row f_r_cnt f_jc_sb">
              <div class="f_col el-p-txt">
                <p class="date-p">{{item.name}}</p>
              </div>
              <el-dropdown trigger="click" @command="dropdownCallBack">
              <span class="el-dropdown-link">
                <i class="el-icon-setting" v-if="item.id === currentId"></i>
              </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </router-link>
          </li>
        </ul>
      <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules"  ref="ruleForm">
          <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
            <el-input v-model="form.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="上传图片" class="margin-bottom-img"></el-form-item>
          <el-upload
            class="avatar-uploader"
            action="/api/spot/uploadAttachment"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="温馨提示"
        :visible.sync="dialogVisible"
        width="30%">
        <span>确定要删除此模块吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleItem(currentId)">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
import PubSub from 'pubsub-js'
import axios from 'axios'
export default {
  name: 'slide-menu-2',
  data () {
    return {
      isFirst: false,
      currentId: '', // 自己当前id
      moduleId: '', // 上级id
      list: [],
      imageUrl: '',
      dialogFormVisible: false,
      dialogVisible: false,
      form: {
        name: '',
        imgPath: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      formTitle: '新增子模块',
      formLabelWidth: ''
    }
  },
  mounted () {
    PubSub.subscribe('SELECTED-MODULE-ID', (event, data) => {
      this.moduleId = data
      this.isFirst = true
      this.getList()
    })
    PubSub.subscribe('REFRESH-SPOT', (event, data) => {
      this.isFirst = data
      this.getList()
    })
  },
  methods: {
    addShowDialog () {
      if (!this.moduleId) {
        this.$message.error('请先新建模块')
        return
      }
      this.dialogFormVisible = true
      this.formTitle = '新增子模块'
      this.form.name = ''
      this.imageUrl = ''
    },
    handleClickItem (id) {
      this.currentId = id
      this.list.find((item, index) => {
        if (item.id === this.currentId) {
          this.pubSpotItemSelected(item)
        }
      })
    },
    getList () {
      let url = `/api/spot/${this.moduleId}/list`
      axios.get(`${url}`)
        .then(res => {
          if (res.data.code === 'S200') {
            this.list = res.data.data
            if (!this.list.length) {
              PubSub.publish('SELECTED-SPOT', {})
            }
            if (this.list.length && this.isFirst) {
              let itemObj = this.list[0]
              // 默认以及菜单选中第一个
              this.currentId = itemObj.id
              this.pubSpotItemSelected(itemObj)
            }
          }
        }, res => {
          console.log('error')
        })
    },
    dropdownCallBack (command) {
      if (command === 'edit') {
        this.dialogFormVisible = true
        this.formTitle = '编辑子模块'
        this.list.find((item, index) => {
          if (item.id === this.currentId) {
            this.form.name = item.name
            this.imageUrl = '/api/attachment/' + item.avatarPath
          }
        })
      }
      if (command === 'del') {
        this.dialogVisible = true
      }
    },
    addItem (obj) {
      let url = `/api/spot/${this.moduleId}/save`
      axios.post(`${url}?name=${obj.name}&avatarPath=${obj.imgPath}`)
        .then(res => {
          this.dialogFormVisible = false
          this.isFirst = false
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    editItem (obj) {
      let url = '/api/spot/updateBasicInfo/' + this.currentId
      axios.post(`${url}?name=${obj.name}&avatarPath=${obj.imgPath}`)
        .then(res => {
          this.dialogFormVisible = false
          this.isFirst = false
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    deleItem (id) {
      let url = '/api/spot/delete/'
      axios.post(`${url}/${id}`)
        .then(res => {
          this.dialogVisible = false
          this.isFirst = true
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.imgPath = res.data
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = {name: this.form.name, imgPath: this.form.imgPath}
          if (this.formTitle === '编辑子模块') {
            this.editItem(obj)
          } else {
            this.addItem(obj)
          }
          this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
      this.imageUrl = ''
    },
    beforeAvatarUpload (file) {
      let allowTypeFlag = false
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        allowTypeFlag = true
      }
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!allowTypeFlag) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isLt2M && allowTypeFlag
    },
    pubSpotItemSelected (itemObj) {
      // 因为EditorVideo第一次无法接收事件，所以发送2次
      for (let i = 0; i < 2; i++) {
        PubSub.publish('SELECTED-SPOT', itemObj)
      }
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.slide-menu-2
  width 350px
  height 100%
  background #fff
  .model-top
    font-size 14px
    color #333
    height 61px;
    line-height 61px
    padding 0 20px
    border-bottom 1px solid #ccc
    box-sizing border-box
    .addBtn
      width 100%
      color #333
      text-align left
  .model-menu-ul
    padding 0
    box-sizing border-box
    .current-li
      background #e0dfdf
    li
      padding 20px 20px
      font-size 12px
      box-sizing border-box
    .el-icon-plus
      font-size 12px
    .el-p
      margin-left 2px
      width 100%
    .el-p-txt
      font-size 14px
      width 100%
      .date-p
        /*margin-bottom 10px*/
        color #333
  .margin-bottom-img
    margin-bottom 0
  .avatar-uploader .el-upload
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden
  .avatar-uploader .el-upload:hover
    border-color: #409EFF
  .avatar-uploader-icon
    font-size: 28px
    color: #8c939d
    width: 178px
    height: 178px
    line-height: 178px
    text-align: center
  .avatar
    width: 178px
    height: 178px
    display: block
</style>
